package com.along.game.action.front;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import bsh.StringUtil;

import com.along.framework.web.BaseAction;
import com.along.game.dao.InitGameDAO;
import com.along.game.dao.PicDAO;
import com.along.game.dao.RoomDAO;
import com.along.game.dao.UserInfoDAO;
import com.along.game.model.Bigpic;
import com.along.game.model.Gamescene;
import com.along.game.model.GameTable;
import com.along.game.model.InitDeskinfo;
import com.along.game.model.OnlineUser;
import com.along.game.model.Smallpic;
import com.along.game.model.SysMenu;
import com.along.game.model.UserInfo;

public class GameAction extends BaseAction {
	 
	@Autowired
	private RoomDAO roomDAO;
	@Autowired
	private InitGameDAO initGameDAO;
	@Autowired
	private PicDAO picDAO;
	@Autowired
	private UserInfoDAO userInfoDAO;
	
	private static final long serialVersionUID = -5360448033041770218L;
	
	//游戏房间所有游戏桌相关信息
	public String gameRoom() throws IOException
	{
		String strRoomId = getRequest().getParameter("roomid");//  游戏房间
		Gamescene gamescene = roomDAO.getRoomInfoById(strRoomId);//得到单个游戏房间信息
		StringBuilder sbMessage = new StringBuilder();
		sbMessage.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
		sbMessage.append("<room name=\""+gamescene.getGamesceneName()+"\" perUserCount=\"4\" tableWidth=\"150\" tableHeight=\"150\"><tables>");
		
		UserInfo userInfo = (UserInfo) this.getSession().getAttribute("userinfo");
		initGameDAO.UpdateOnlineUserRoomId(strRoomId,userInfo.getUsn());//更新用户的房间信息
		
		List roomlist = new ArrayList();//游戏桌
		roomlist = roomDAO.getAllRoom(strRoomId);//
		Iterator roomIterator = roomlist.iterator();
		while(roomIterator.hasNext())
		{
			GameTable gameTable = (GameTable)roomIterator.next();
			sbMessage.append("<gameTable id=\""+gameTable.getDesk_id()+"\" name=\""+gameTable.getDesk_id()+"\"/>");
			
			List list = new ArrayList();
			list = roomDAO.getPlayerByDeskId(gameTable.getDesk_id());//通过游戏桌id得到在线的游戏桌状态,包括人
			Iterator onineUserlist = list.iterator();	
			while(onineUserlist.hasNext()){
				OnlineUser onlineUser = (OnlineUser)onineUserlist.next();
				sbMessage.append("<place position=\""+onlineUser.getDeskLocation()+"\" type=\""+onlineUser.getUserSex()+"\" status=\""+onlineUser.getUserState()+"\"/>");//得到游戏中桌子信息
			}
		}
		sbMessage.append("</tables></room>");
		getResponse().setCharacterEncoding("utf-8");
		getResponse().getWriter().write(sbMessage.toString());
		return null;
	}

	//游戏正在玩的图片信息
	public String gamePlay() throws IOException
	{
		StringBuilder sbMessage = new StringBuilder();
		sbMessage.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
		sbMessage.append("<root><sourceImage image=\"../resource/7/0.jpg\"/><anchors><anchor image=\"../resource/7/1.jpg\" x=\"174\" y=\"101\"/><anchor image=\"../resource/7/5.jpg\" x=\"0\" y=\"388\"/><anchor image=\"../resource/7/11.jpg\" x=\"196\" y=\"215\"/><anchor image=\"../resource/7/4.jpg\" x=\"327\" y=\"168\"/><anchor image=\"../resource/7/19.jpg\" x=\"327\" y=\"349\"/></anchors></root>");
		getResponse().setCharacterEncoding("utf-8");
		getResponse().getWriter().write(sbMessage.toString());
		return null;
	}
	
	//游戏正在玩的图片信息
	public String games1() throws IOException
	{
		//String desk_id = getParameter("desk_id");
		String usn = getParameter("usn");  //用户usn
		OnlineUser onlineUser = roomDAO.getOnlineInfoByUsn(usn);
		Integer pic = onlineUser.getBigPic().intValue();   //当前玩的图片位置

		String playbiPic[] = roomDAO.getBigPicByDeskId(onlineUser.getDeskId()+"");//通过游戏桌得到所有的图片
		
		String bigpicId = playbiPic[pic] ;//得到图片位置得到大图片id
		
		Bigpic bigPic = roomDAO.getBigPicInfoById(bigpicId);//通过大图片id得到大图片信息
		InitDeskinfo initDeskInfo = picDAO.getInitDeskByDeskId(onlineUser.getDeskId()+"");
		String smallPics= initDeskInfo.getSmallpicOrder();
		String arrysmallpic = StringUtil.split(smallPics, "|")[pic];//得到小图片，以逗号隔开，如2,3,23,32,322
		
		List listsmallPic = roomDAO.getSmallPicInfoById(arrysmallpic);//通过大图片和桌子信息得到所有的小图片
		
		StringBuilder sbMessage = new StringBuilder();
		sbMessage.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
		sbMessage.append("<room>");
		sbMessage.append("<sourceImage image=\""+bigPic.getPicUrl()+"\"/>");
		sbMessage.append("<anchors>");
		
		Iterator smallpicLists = listsmallPic.iterator(); 			
		while(smallpicLists.hasNext()){
			Smallpic smallPic = (Smallpic)smallpicLists.next();
			sbMessage.append("<anchor image=\""+smallPic.getPicUrl()+"\" x=\""+smallPic.getPic_x()+"\" y=\""+smallPic.getPic_y()+"\"/>");
		}
		sbMessage.append("</anchors>");
		sbMessage.append("</room>");
		getResponse().setCharacterEncoding("utf-8");
		getResponse().getWriter().write(sbMessage.toString());
		return null;
	}
	
	//游戏场树
	public String gameTree() throws IOException
	{
		StringBuilder sbMessage = new StringBuilder();
		sbMessage.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
		sbMessage.append("<root>");
		sbMessage.append("<games>");
		sbMessage.append("<top background=\"../resource/common/topbg.jpg\" logo=\"../resource/common/logo.png\"/>");
		sbMessage.append("<game label=\"美女找茬\">");
		sbMessage.append(" <team label=\"电信专区\">");
		
		List list = new ArrayList();
		list = roomDAO.getSceneInfo2();//游戏场
		Iterator sSceneIt = list.iterator(); 			
		while(sSceneIt.hasNext()){
			Gamescene gameScene = (Gamescene)sSceneIt.next();
			sbMessage.append("<team label=\""+gameScene.getGamesceneName()+"\"/>");
			
			List roomlist = roomDAO.getSceneInfoBydeskId(gameScene.getFiledId()+"");
			Iterator itRooms = roomlist.iterator(); 
			while(itRooms.hasNext()){
				Gamescene Gamescene1 = (Gamescene)itRooms.next();
				String strUrl = "http://202.103.95.216:88/";
				sbMessage.append("<team label=\""+Gamescene1.getGamesceneName()+"("+roomDAO.getUserCountByRoomId(Gamescene1.getFiledId()+"")+")"+"\" url=\""+strUrl+"gameinfo/game_gameRoom.do?roomid="+Gamescene1.getFiledId()+"\"/>");
				//sbMessage.append("<team label=\""+Gamescene1.getGamesceneName()+"("+roomDAO.getUserCountByRoomId(Gamescene1.getFiledId()+"")+")"+"\" url=\""+getBasePath()+"gameinfo/game_gameRoom.do?roomid="+Gamescene1.getFiledId()+"\"/>");
			}
		}
		sbMessage.append("</team>");
		sbMessage.append("</game>");
		sbMessage.append("</games>");
		sbMessage.append("</root>");
		getResponse().setCharacterEncoding("utf-8");
		getResponse().getWriter().write(sbMessage.toString());
		return null;
	}
	
	//取得房间所有用户信息列表
	public String getFriend() throws IOException
	{
		String sceneId = getParameter("roomid");//房间
		StringBuilder sbMessage = new StringBuilder();
		sbMessage.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
		sbMessage.append("<root>");
		List list = new ArrayList();
		
		list = roomDAO.getPlayerBySceneId(sceneId);
		Iterator sSceneIt = list.iterator(); 			
		while(sSceneIt.hasNext()){
			OnlineUser onlineUser = (OnlineUser)sSceneIt.next();
			sbMessage.append("<item name=\""+onlineUser.getUsn()+"\" level=\""+onlineUser.getUserGradename()+"\" amount=\""+onlineUser.getPoints()+"\"/>");
		}
		sbMessage.append("</root>");
		getResponse().setCharacterEncoding("utf-8");
		getResponse().getWriter().write(sbMessage.toString());
		return null;
	}
	
	
	//游戏中，所有玩家的状态信息
	public String gameRoomPlayerStatus() throws IOException
	{
		String deskid = getParameter("desk_id");//传入桌子id参数
		
		UserInfo userinfo = (UserInfo) this.getRequest().getSession().getAttribute("userinfo");
		String usn = userinfo.getUsn();
		StringBuilder sbMessage = new StringBuilder();
		sbMessage.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
		sbMessage.append("<root>");
		
		List list = new ArrayList();
		list = roomDAO.getPlayerByDeskId(deskid);
		Iterator sSceneIt = list.iterator(); 						
		while(sSceneIt.hasNext()){
			String isme = "false",startGame="false",gameOver="false";//是否是本人
			OnlineUser onlineUser = (OnlineUser)sSceneIt.next();
			if(usn!=null&&usn.equals(onlineUser.getUsn()))
			{
				isme = "true";
			}
			String start1 = onlineUser.getUserState();
			if("1".equals(start1))//用户状态为1时，为已经开始游戏
				startGame = "true";
			if("1".equals(onlineUser.getIfEnd()))//是否结束
			{
				gameOver = "true";
			}
			sbMessage.append("<player id=\""+onlineUser.getUsn()+"\" type=\"1\" name=\""+onlineUser.getUserName()+"\" amount=\""+onlineUser.getPoints()+"\" pictureIndex=\""+onlineUser.getBigPic()+"\" blockCount=\""+onlineUser.getHits()+"\" isme=\""+isme+"\" startGame=\""+startGame+"\" gameOver=\""+gameOver+"\"/>");
			
		}
		sbMessage.append("</root>");
		getResponse().setCharacterEncoding("utf-8");
		getResponse().getWriter().write(sbMessage.toString());
		return null;
	}
	
	//游戏桌准备信息
	public String gameRoomReady() throws IOException
	{
		String disk_id = getParameter("desk_id");
		StringBuilder sbMessage = new StringBuilder();
		sbMessage.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
		sbMessage.append("<root>");
		
		List list = new ArrayList();
		list = roomDAO.getPlayerByDeskId(disk_id);
		Iterator sSceneIt = list.iterator(); 			
		while(sSceneIt.hasNext()){
			OnlineUser onlineUser = (OnlineUser)sSceneIt.next();
			sbMessage.append("<item id=\""+onlineUser.getUsn()+"\" type=\""+onlineUser.getUserSex()+"\" name=\""+onlineUser.getUserName()+"\" amount=\""+onlineUser.getPoints()+"\" say=\"\" status=\""+onlineUser.getUserState()+"\"/>");
		}
		sbMessage.append("</root>");
		getResponse().setCharacterEncoding("utf-8");
		getResponse().getWriter().write(sbMessage.toString());
		return null;
	}
	
	/**
	 * 是否找到了茬
	 * @return
	 * @throws IOException 
	 */
	public String clickBlock() throws IOException
	{
		//String picid = getParameter("picid");
		String smallid = getParameter("smallid");
		String deskid = getParameter("desk_id");
		String indexstr = getParameter("pictureIndex");
		int index1 = Integer.parseInt(indexstr);
		String pics[] = roomDAO.getBigPicByDeskId(deskid);
		String picid = pics[index1];
		
		StringBuilder sbMessage = new StringBuilder();
		sbMessage.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
		
		List list = roomDAO.getSmallPicInfoById(deskid,picid);
		Iterator sSceneIt = list.iterator(); 			
		while(sSceneIt.hasNext()){
			Smallpic smallpic = (Smallpic)sSceneIt.next();
		  if(smallid.equals(smallpic.getId()+""))
		  {
			  sbMessage.append("<game><result flag=\"true\"/></game>"); 
			  break;//如果是点点的荐则会选中
		  }
		  else
		  {
			  sbMessage.append("<game><result flag=\"false\"/></game>"); 
		  }
		}
		
		sbMessage.append("<game><result flag=\"true\"/></game>");
		getResponse().setCharacterEncoding("utf-8");
		getResponse().getWriter().write(sbMessage.toString());
		return null;
	}
	
	
	/**
	 * 点中通知，更改用户的找茬数
	 * @return
	 * @throws IOException
	 */
	public String clickNotify() throws IOException
	{
		String usn = getParameter("usn");
//		UserInfo userInfo = (UserInfo) this.getSession().getAttribute("userinfo");
//		String usn = userInfo.getUsn();
		StringBuilder sbMessage = new StringBuilder();
		sbMessage.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
		
		int i = initGameDAO.UpdateHitsCount(usn);//更新找茬数
		String strResult = "0";
		if(i>=1)
			strResult = "1";
		sbMessage.append("<game><result flag=\""+strResult+"\"/></game>");
		getResponse().setCharacterEncoding("utf-8");
		getResponse().getWriter().write(sbMessage.toString());
		return null;
	}
	
	
	//方位确认
	public String enterTableConfirm_bak() throws IOException
	{
		String disk_id = getParameter("desk_id");
		StringBuilder sbMessage = new StringBuilder();
		sbMessage.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
		
		List list = new ArrayList();
		list = roomDAO.getPlayerByDeskId(disk_id);
		Iterator onlineuserIer = list.iterator(); 
		String str = "";
		String strResult = "1";
		int i = 0;
		while(onlineuserIer.hasNext()){
			OnlineUser onlineUser = (OnlineUser)onlineuserIer.next();
			String loca = onlineUser.getDeskLocation();
			if("1".equals(loca))
			{
				str = str+"1,";
				i++;
			}
			if("2".equals(loca))
			{
				str = str+"2,";
				i++;
			}
			
			
			if("3".equals(loca))
			{
				str = str+"3,";
				i++;
			}
			
			if("4".equals(loca))
			{
				str = str+"4";
				i++;
			}
			
			
		}
		if(i==4)
		{
			strResult  = "\"0\"";
		}
		String substr = "";
		if(str.contains("1"))
		{
			substr +=  " left=\"1\"";
		}
		if(!str.contains("1"))
		{
			substr +=  " left=\"0\"";
		}
		if(str.contains("2"))
		{
			substr +=  " top=\"1\"";
		}
		if(!str.contains("2"))
		{
			substr +=  " top=\"0\"";
		}
		
		if(str.contains("3"))
		{
			substr +=  " right=\"1\"";
		}
		if(!str.contains("3"))
		{
			substr +=  " right=\"0\"";
		}
		if(str.contains("4"))
		{
			substr +=  " bottom=\"1\"";
		}
		if(!str.contains("4"))
		{
			substr +=  " bottom=\"0\"";
		}
		
		
		sbMessage.append("<root result=\""+strResult+"\""+substr+"></root>");
		getResponse().setCharacterEncoding("utf-8");
		getResponse().getWriter().write(sbMessage.toString());
		return null;
	}
	
	
	//方位确认,判断是事可以入坐
	public String enterTableConfirm() throws IOException
	{
		String disk_id = getParameter("desk_id");
		String position = getParameter("position");
		StringBuilder sbMessage = new StringBuilder();
		sbMessage.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
		UserInfo userInfo = (UserInfo) this.getSession().getAttribute("userinfo");
		
		List list = new ArrayList();
		boolean boolIf = roomDAO.ifHavaPositionByDeskId(disk_id,position);
		String strResult = "0";
		if(!boolIf)//如果可以入座
		{
			strResult = "1";
			initGameDAO.SaveRoomInfoByLocalId(disk_id,position,userInfo.getUsn());//更新这个人的方位信息
			
		}
		
		sbMessage.append("<root result=\""+strResult+"\"></root>");
		getResponse().setCharacterEncoding("utf-8");
		getResponse().getWriter().write(sbMessage.toString());
		return null;
	}
	
	/**
	 * 点击游戏“开始”按钮时，设置用户的状态为开始游戏状态 
	 * @return
	 * @throws IOException
	 */
	public String startGame() throws IOException
	{
		OnlineUser onlineUser = new OnlineUser();
		UserInfo userInfo = (UserInfo) this.getSession().getAttribute("userinfo");
		String usn = userInfo.getUsn();
		int i  = initGameDAO.UpdateUserStateStateByUsn("1", usn);
		String isResult = "0";
		if(i>=1)
		{
			isResult = "1";
		}
		StringBuilder sbMessage = new StringBuilder();
		sbMessage.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
		sbMessage.append("<root result=\""+isResult+"\"></root>");
		getResponse().setCharacterEncoding("utf-8");
		getResponse().getWriter().write(sbMessage.toString());
		return null;
	}
	
	/**
	 * 每局游戏结束后,把桌子的用户都设置为准备状态
	 * @return
	 * @throws IOException
	 */
	public String endGame() throws IOException
	{
//		OnlineUser onlineUser = new OnlineUser();
//		UserInfo userInfo = (UserInfo) this.getSession().getAttribute("userinfo");
//		String usn = userInfo.getUsn();
		String disk_id = getParameter("desk_id");//传入桌子id
		int i  = initGameDAO.UpdateDeskStateStateByDeskId("0", disk_id);//设置桌子的用户都为准备状态 
		String isResult = "0";
		if(i>=1)
		{
			isResult = "1";
		}
		StringBuilder sbMessage = new StringBuilder();
		sbMessage.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
		sbMessage.append("<root result=\""+isResult+"\"></root>");
		getResponse().setCharacterEncoding("utf-8");
		getResponse().getWriter().write(sbMessage.toString());
		return null;
	}
	
	/**
	 * 游戏结束后，显得所有用户的得分情况
	 * @return
	 * @throws IOException
	 */
	public String endGameShowInfo() throws IOException
	{
		String disk_id = getParameter("desk_id");//传入桌子id
		StringBuilder sbMessage = new StringBuilder();
		sbMessage.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
		sbMessage.append("<root>");
		
		int intscore = 0;//未计算
		String strScore = "<score>";
		
		List list = new ArrayList();
		list = roomDAO.getPlayerByDeskId(disk_id);
		Iterator sSceneIt = list.iterator();		
		while(sSceneIt.hasNext()){
			OnlineUser onlineUser = (OnlineUser)sSceneIt.next();
			if("1".equals(onlineUser.getIfEnd()))//如果为游戏结束状态
			{
				sbMessage.append("<item id=\""+onlineUser.getUsn()+"\" type=\""+onlineUser.getUserSex()+"\" name=\""+onlineUser.getUserName()+"\" amount=\""+onlineUser.getPoints()+"\" say=\"\" status=\""+onlineUser.getUserState()+"\"/>");
				strScore += "<item id=\""+onlineUser.getUsn()+"\" name=\""+onlineUser.getUserName()+"\" score=\""+intscore+"\" chacount=\""+onlineUser.getHits()+"\" combocount=\""+onlineUser.getCombocount()+"\"/>";
			}
		}
		strScore += "</score>";
		sbMessage.append(strScore);
		sbMessage.append("</root>");
		
		
		//int i  = initGameDAO.UpdateUserEndStateByDeskId("0","0",disk_id);//设置桌子的用户都为准备状态 
		
		getResponse().setCharacterEncoding("utf-8");
		getResponse().getWriter().write(sbMessage.toString());
		return null;
	}
	
	/**
	 * 用户关闭游戏窗口，回到房间
	 * @return
	 * @throws IOException
	 */
	public String closeWindows() throws IOException
	{
//		UserInfo userInfo = (UserInfo) this.getSession().getAttribute("userinfo");
//		String usn = userInfo.getUsn();
		String usn = getParameter("usn");//传入桌子id
		int i  = initGameDAO.UpdateDeskStateStateByUsn("0",usn);//设置用户都为准备状态 
		String isResult = "0";
		if(i>=1)
		{
			isResult = "1";
		}
		StringBuilder sbMessage = new StringBuilder();
		sbMessage.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
		sbMessage.append("<root result=\""+isResult+"\"></root>");
		getResponse().setCharacterEncoding("utf-8");
		getResponse().getWriter().write(sbMessage.toString());
		return null;
	}
	
	
	/**
	 * 用户关闭窗口时，从在线表中删除用户
	 * @return
	 * @throws IOException
	 */
	public String exitGame() throws IOException
	{
//		UserInfo userInfo = (UserInfo) this.getSession().getAttribute("userinfo");
//		String usn = userInfo.getUsn();
		String usn = getParameter("usn");//传入桌子id
		int i  = initGameDAO.DeleteOnlineUserByUsn(usn);//设置桌子的用户都为准备状态 
		String isResult = "0";
		if(i>=1)
		{
			isResult = "1";
		}
		StringBuilder sbMessage = new StringBuilder();
		sbMessage.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
		sbMessage.append("<root result=\""+isResult+"\"></root>");
		getResponse().setCharacterEncoding("utf-8");
		getResponse().getWriter().write(sbMessage.toString());
		return null;
	}
	
	
	/**
	 * 一个人玩完游戏，马上通知后台
	 * @return
	 * @throws IOException
	 */
	public String notifyEnd() throws IOException
	{
//		UserInfo userInfo = (UserInfo) this.getSession().getAttribute("userinfo");
//		String usn = userInfo.getUsn();
		String usn = getParameter("usn");//传入桌子id
		int i  = initGameDAO.UpdateUserEndStateByUsn("1", usn);//设置桌子的用户都为准备状态 
		String isResult = "0";
		if(i>=1)
		{
			isResult = "1";
		}
		StringBuilder sbMessage = new StringBuilder();
		sbMessage.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
		sbMessage.append("<root result=\""+isResult+"\"></root>");
		getResponse().setCharacterEncoding("utf-8");
		getResponse().getWriter().write(sbMessage.toString());
		return null;
	}
	
	/**
	 * 游戏开始时，按游戏桌重设游戏状态
	 * @return
	 * @throws IOException
	 */
	public String resetGame() throws IOException
	{
		String desk_id = getParameter("desk_id");//传入桌子id
		int i  = initGameDAO.UpdateDeskInit(desk_id);//设置桌子的用户都为清0状态
		String isResult = "0";
		if(i>=1)
		{
			isResult = "1";
		}
		StringBuilder sbMessage = new StringBuilder();
		sbMessage.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
		sbMessage.append("<root result=\""+isResult+"\"></root>");
		getResponse().setCharacterEncoding("utf-8");
		getResponse().getWriter().write(sbMessage.toString());
		return null;
	}
	
	

}
